#include "slist.h"
#define _CRT_SECURE_NO_WARNINGS 1

void SListDestroy1(SListNode** plist)
{
	if (*plist == NULL)
		return;
	SListDestroy1(&(*plist)->next);
	free(*plist);
	*plist = NULL;
}

void SListDestroy2(SListNode** plist)
{
	while (*plist != NULL)
	{
		SListNode* p = (*plist)->next;
		free(*plist);
		*plist = p;
	}
	*plist = NULL;
}

SListNode* BuySListNode(SLTDateType x)
{
	SListNode* plist = (SListNode*)malloc(sizeof(SListNode));
	plist->data = x;
	plist->next = NULL;
	return plist;
}

void SListPrint(SListNode* plist)
{
	while (plist != NULL)
	{
		printf("%d->", plist->data);
		plist = plist->next;
	}
	printf("NULL\n");
}

void SListPushBack(SListNode** pplist, SLTDateType x)
{
	assert(pplist);
	SListNode* p = BuySListNode(x);
	if (*pplist == NULL)
	{
		*pplist = p;
	}
	else
	{
		SListNode* plist = *pplist;
		while (plist->next != NULL)
			plist = plist->next;
		plist->next = p;
	}
}

void SListPushFront(SListNode** pplist, SLTDateType x)
{
	assert(pplist);
	SListNode* p = BuySListNode(x);
	if (*pplist != NULL)
		p->next = *pplist;
	*pplist = p;
}

void SListPopBack(SListNode** pplist)
{
	assert(pplist);
	if (*pplist == NULL)
		return;
	else if ((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}
	else
		while ((*pplist)->next->next != NULL)
		{
			free((*pplist)->next);
			(*pplist)->next = NULL;
		}
}

void SListPopFront(SListNode** pplist)
{
	assert(pplist);
	if (*pplist == NULL)
		return;
	else if ((*pplist)->next == NULL)
	{
		free((*pplist)->next);
		*pplist = NULL;
	}
	else
	{
		SListNode* p = (*pplist)->next;
		free(*pplist);
		*pplist = p;
	}
}

SListNode* SListFind(SListNode* plist, SLTDateType x)
{
	while (plist != NULL)
	{
		if (plist->data == x)
			return plist;
		plist = plist->next;
	}
	return NULL;
}

void SListInsertAfter(SListNode* pos, SLTDateType x)
{
	SListNode* p = BuySListNode(x);

	if((pos)->next == NULL)
	{
		(pos)->next = p;
	}
	else
	{
		p->next = (pos)->next;
		(pos)->next = p;
	}
}

void SListEraseAfter(SListNode* pos)
{
	if (pos == NULL)
		return;
	SListNode* p = pos->next->next;
	free(pos->next);
	pos->next = p;
}
